package com.ruoyi.client.controller;

import com.ruoyi.activity.model.domain.User;
import com.ruoyi.client.model.dto.ApiUserLoginRequest;
import com.ruoyi.client.model.dto.ApiUserUpdateRequest;
import com.ruoyi.activity.service.IUserService;
import com.ruoyi.client.vo.ApiLoginUserVO;
import com.ruoyi.client.vo.UserLoginVO;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.base.BaseException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.ruoyi.client.model.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/api/user")
public class ApiUserController {

    @Resource
    private IUserService userService;


    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public AjaxResult userLogin(@RequestBody ApiUserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BaseException("请求参数错误");
        }
        String account = userLoginRequest.getAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(account, userPassword)) {
            throw new BaseException("请求参数错误");
        }
        UserLoginVO userLogin = userService.userLogin(account, userPassword, request);
        return AjaxResult.success(userLogin);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public AjaxResult userLogout(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        System.out.println((UserLoginVO) request.getSession().getAttribute(USER_LOGIN_STATE));
        boolean result = userService.userLogout(request);
        return AjaxResult.success(result);
    }

    /**
     * 更新用户密码
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public AjaxResult updateUser(@RequestBody ApiUserUpdateRequest userUpdateRequest,
                                 HttpServletRequest request) {
        if (userUpdateRequest == null) {
            return null;
        }
        UserLoginVO loginUserVO = userService.getUserLoginVO(request);
        if (loginUserVO == null) {
            throw new BaseException("您还未登录");
        }
        boolean result = userService.updateById(userUpdateRequest, loginUserVO);
        if (!result) {
            return null;
        }
        return AjaxResult.success(true);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public AjaxResult getLoginUser(HttpServletRequest request) {
        UserLoginVO loginUserVO = userService.getUserLoginVO(request);
        return AjaxResult.success(loginUserVO);
    }
}
